/**
 * Created by James on 2015/9/5.
 */
//AngularJS 控制器



grApp.controller('ConfirmCtrl',['$scope',
    '$http',
    'ConfirmFactory','BaseService',
    function($scope,$http,confirmFactory,BaseService){

        //window.onunload = function(){alert('该窗口已经被关闭！.')}

        $scope.wx_inited = false;
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        }else{
            onBridgeReady();
        }
        function onBridgeReady(){
            $scope.wx_inited = true;
        }

        $scope.je = 0;
        $scope.yhje = 0;
        $scope.ohome = {gCoin:0,gCoinState:0,checkCoin:false} ;
        $scope.load = function(je,yhje,hyje,balance,total,aid,sjc,bq_flag,gCoin){

            $scope.je = parseFloat(je).toFixed(2);
            $scope.yhje = parseFloat(parseFloat(yhje).toFixed(2));
            $scope.hyje = parseFloat(parseFloat(hyje).toFixed(2));
            $scope.balance = parseFloat(parseFloat(balance).toFixed(2));
            $scope.total = parseFloat(parseFloat(total).toFixed(2));
            $scope.aid = aid;
            $scope.sjc = sjc;
            $scope.finalAmount = parseFloat(je).toFixed(2)-($scope.par||0);
            $scope.bq_flag = bq_flag;
            $scope.ohome.gCoin = gCoin ;
        }
        $scope.checkCoin = false ;
        $scope.checkGcoin = function(checkCoin){
            var total = $scope.total, finalAmount = $scope.je-($scope.par||0);
            //$scope.checkCoin = checkCoin ;
            //alert('活动余额一经使用，无法返还（除无货退单外），敬请谅解。'+$scope.checkCoin);
            if(checkCoin){
                alert("活动余额一经使用，无法返还（除无货退单外），敬请谅解。");
                $scope.ohome.checkCoin = true ;
                finalAmount = finalAmount - $scope.ohome.gCoin
                $scope.ohome.gCoinState = $scope.ohome.gCoin ;
            }else{
                $scope.ohome.checkCoin = false ;
                $scope.ohome.gCoinState = 0 ;
            }
            $scope.total = total ;
            $scope.finalAmount = finalAmount ;
        };
        var allAddrModal = angular.element('#form-alert');
        var allCouponModal = angular.element('#form-alert1');

        confirmFactory.getAddressList().then(function(data) {  // 调用承诺API获取数据 .resolve
            $scope.sendAddr=[];
            $scope.data=data;

            angular.forEach($scope.data,function(data,index,array){
                if($scope.aid == 0){
                    if(data.isDefault==true){
                        $scope.sendAddr = data;
                        $scope.addrId = data.objectId;
                    }
                }else{
                    if(data.objectId==$scope.aid){
                        $scope.sendAddr = data;
                        $scope.addrId = data.objectId;
                    }
                }

            });

        });

        confirmFactory.getCouponList().then(function(data) {  // 调用承诺API获取数据 .resolve
            $scope.couponList=data;
        });

        $scope.getAllAddr = function(){
            allAddrModal.modal();
        },
        $scope.setSendAddr = function(index,data){
            $scope.sendAddr = data;
            $scope.addrId = data.objectId;
            allAddrModal.modal("close");
        },
        $scope.getAllCoupon = function(){
            allCouponModal.modal();
        },
        $scope.setSendCoupon = function(index,data){
            $scope.sendCoupon = data;
            $scope.couponId = data.objectId;
            $scope.par = parseFloat(parseFloat(data.coupon.par).toFixed(2));

            $scope.finalAmount = $scope.je-($scope.par||0)-($scope.ohome.checkCoin?$scope.ohome.gCoin:0);
            allCouponModal.modal("close");
        },
        $scope.addOrder=function(index){

            var addrId = $scope.addrId;
            var finalAmount = $scope.finalAmount;

            if(addrId == null || addrId == ''){
                alert('收货地址不能为空，请先选择自己的收货地址。');
                return false;
            }

            if(finalAmount != 0 && (finalAmount == null || finalAmount == '')){
                alert('订单金额不能为空');
                window.location.href='/cart';
                return false;
            }

            if(finalAmount <= 0){
                alert('订单金额不能为0');
                window.location.href='/cart';
                return false;
            }

            var ecconfirm = window.confirm("尊敬的果粉，准备开始下单了，请您确定的收货地址是正确的，商品将会快速前往您的收货地址。如果您确定地址正确，请点击‘确定’按钮继续下单。");
            if (!ecconfirm) {
               return;
            }

            document.getElementById("qr").disabled=true;
            var strMJ=  angular.element("#strMJ").val(); //获取满减活动名称
            var remark =(strMJ || '') +"/"+ ($scope.remark || '');
            var total = $scope.total;
            var radioPay = document.getElementsByName("radioPay");
            var balance = $scope.balance;
            var couponId = $scope.couponId;
            var par = $scope.par;
            var sjc = $scope.sjc;


            var payway;
            for(var i=0;i<radioPay.length;i++)
            {
                if(radioPay[i].checked)
                    payway=radioPay[i].value;
            }

            if(payway =='ye_pay') {
                if (parseFloat(balance) < parseFloat(finalAmount)) {
                    alert('余额不足，请选择微信支付或货到付款');
                    document.getElementById("qr").disabled=false;
                    return false;
                }
            }

            //取消支付需要再调起
            var wxpay = function(orderid,fee){
                BaseService.wxpay(orderid,fee).then(function(data){
                    //更新状态为1500
                    BaseService.wx_wait(orderid).then(function(data) {  // 调用承诺API获取数据 .resolve

                        window.location.href='/user/history/3';
                    });
                }).catch(function(err){
                    if(err.err_msg.indexOf('cancel')>0){
                        //取消支付
                        if(confirm('是否真的取消支付?\n取消之后,订单将会出现在您的待付款列表中保存2个小时!')){
                            window.location.href='/order/confirmOrder/again';
                            return;
                        };
                        wxpay(orderid,fee);
                        return;
                    }
                    if(err.err_msg.indexOf('fail')>0){
                        //支付失败
                        alert("您的微信支付操作失败~\n可能是您的密码忘记了吧?\n何不尝试用货到付款呢?");
                        return;
                    }
                    //其他异常信息
                    alert("请求微信支付失败~可能是我们的工程师正在更新系统,何不尝试用货到付款呢?");
                    window.location.href='/order/confirmOrder/again';
                });
            };

            confirmFactory.addOrder(remark,finalAmount,total,addrId,payway,couponId,par,sjc,$scope.ohome.checkCoin,$scope.ohome.gCoinState).then(function(data){

                if(data.code == 0){
                    if(payway =='wx_pay'){
                        var orderid = data.orderid;
                        var fee = data.fee;
                        if($scope.wx_inited){
                            wxpay(orderid,fee);
                        }else{
                            alert('网络链接速度过慢，微信支付未能初始化成功~\n请刷新重试一下');
                            window.location.href='/order/confirmOrder/again';
                        }
                    }else{
                        alert("下单成功");
                        window.location.href='/user/history/0';
                    }
                }else{
                    if(data.code == 505){
                        alert("已下单，现帮您跳到我的订单");
                        window.location.href='/user/history/0';
                    }else if(data.code == 506){
                        alert("订单创建失败，购买商品数量为0");
                        window.location.href='/cart';
                    }else if(data.code == 507){
                        alert("订单创建失败，所选地址异常，请联系客服");
                        window.location.href='/cart';
                    }else if(data.code == 516){
                        alert("商品库存不足，请重新选择商品");
                    }else{
                        alert("订单创建失败，请联系客服");
                        window.location.href='/order/confirmOrder/again';
                    }
                }
            });
        },
        $scope.toAddAdder=function(sjc_str){
            //alert(1);
            //alert(sjc_str);
            var url = '/order/confirmOrder/0_'+sjc_str;

            window.location.href='/user/center/address?back='+url;
        }


}]);

//创建工厂/Service
grApp.factory('ConfirmFactory',['$http', '$q', function ($http, $q){
    var service={};

    //用户地址
    service.getAddressList= function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/user/center/getAddress'
            }).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };

    //用户可用的优惠券
    service.getCouponList= function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'POST',
            url: '/user/center/getUserCouponsListConfirm'
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    //读取全场满减规则是否满足返回优惠金额
    service.getActivityRuleMJ= function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/getActivityRuleMJAjax'
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    //生成订单
    service.addOrder= function (remark,finalAmount,total,addrId,payway,couponId,par,sjc,gCoinChecked,gCoin) {

        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行

        $http({
            method: 'GET',
            url: '/order/addOrder',
            params:{remark:remark,finalAmount:finalAmount,total:total,addrId:addrId,payway:payway,couponId:couponId,par:par,sjc:sjc,gCoinChecked:gCoinChecked,gCoin:gCoin}
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };
    return service;
}]);